<template>
  <validate-form @form-submit="submitFn">
    <div class="mb-3">
      <label class="form-label">邮箱地址</label>
      <validate-input :rule="emailRules" v-model="vala.emailValue" type="text" placeholder="请输入邮箱地址"></validate-input>
    </div>
    <div class="mb-3">
      <label for="exampleInputPassword1" class="form-label">密码</label>
      <validate-input :rule="passwordRules" v-model="vala.passwordValue" type="password" placeholder="请输入密码" autocomplete="tel"></validate-input>
    </div>
  </validate-form>
  <div>邮箱: 123@163.com 密码：123456</div>
</template>

<script lang="ts">
import { defineComponent, reactive } from 'vue'

import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { GlobalDataProps } from '../store'
import ValidateInput, { Rule } from '../components/ValidateInput.vue'
import Message from '../components/createMessage'
import ValidateForm from '../components/ValidateForm.vue'
export default defineComponent({
  name: 'Login',
  components: {
    ValidateInput,
    ValidateForm
  },
  setup () {
    const router = useRouter()
    const store = useStore<GlobalDataProps>()
    // 定义邮箱的验证类型数组
    const emailRules: Rule = [
      { type: 'required', message: '不能为空' },
      { type: 'email', message: '邮箱格式不正确' },
      { type: 'range', message: '请输入6-12位邮箱格式' }
    ]
    // 定义密码的验证类型数组
    const passwordRules: Rule = [
      { type: 'required', message: '不能为空' },
      {
        type: 'range',
        min: {
          message: '你的密码至少包括六位，不能含有空格',
          length: 6
        },
        max: {
          message: '你的密码最多包括12位，不能含有空格',
          length: 12
        }
      }
    ]
    // input框双向绑定值
    const vala = reactive({
      emailValue: '',
      passwordValue: ''
    })

    const submitFn = (sub: boolean) => { // 登录按钮监听器
      if (sub) { // sub 输入验证是否通过
        const userData = { // 获取input框内容
          email: vala.emailValue,
          password: vala.passwordValue
        }
        // 触发 vuex  actions--postLogin
        // 使用 返回的async 函数上的then方法
        store.dispatch('tokenCurrent', userData).then(res => {
          Message('登录成功，2秒后自定跳转', 'success')
          setTimeout(() => {
            router.push('/')
          }, 2000)
          return res
        }).catch(err => {
          console.log(err, 12312)
        })
      }
    }

    return {
      emailRules,
      passwordRules,
      vala,
      submitFn
    }
  }
})
</script>
